<template>
    <!-- 信道域 -->
    <div style="position: relative;">
        <div class="width100 height100 flex-column" :class="layout == 'one' ? 'one' : 'all'"
            style="position: absolute;">
            <div class="back flex width100" :class="layout == 'one' ? 'flex1' : 'flex-column flex2'">
                <!-- 3d图合集 -->
                <div class="chart3D flex1" :id="chartAllId"></div>
                <div class="chart3D-right-table flex flex1">
                    <div class="chart3D-table" style="position: relative;overflow: auto;">
                        <acrossTable style="position: absolute;height: 100%;" :layout="layout" :columns="columns"
                            :data="tableData"></acrossTable>
                    </div>
                    <div class="radar" style="position: relative;">
                        <!-- 雷达图 -->
                        <div :id="radarDomId" class="width100 height100"></div>
                        <div class="radar-input">
                            <span class="input-label">选择日期:</span>
                            <el-date-picker v-model="query.date" :clearable="false" type="datetime" placeholder="选择日期时间"
                                @change="changeTime" format="yyyyMMdd HH" value-format="yyyyMMdd HH">
                            </el-date-picker>
                        </div>
                    </div>
                </div>
            </div>
            <div class="back flex1 boxplot-box" v-if="layout == 'one'" key="all">
                <div class="boxplot back float-left" v-for="item, index in boxplotList" :key="index + item.url">
                    <boxplot :layout="layout" :change="change" :name="item.name" :url="item.url" :socketObj="socketObj"
                        :datay1="item.datay1" :datay2="item.datay2">
                    </boxplot>
                </div>
            </div>
            <!-- <div v-else class="back flex1 width100 height100 boxplot-box"> -->
            <el-tabs v-else v-model="activeName" class="boxplot-box flex1 flex-column">
                <el-tab-pane v-for="item, index in boxplotList" :name="item.url" :label="item.name">
                    <boxplot class="width100 height100" :layout="layout" :change="change" :name="item.name"
                        :url="item.url" v-if="activeName == item.url" :socketObj="socketObj" :datay1="item.datay1"
                        :datay2="item.datay2"></boxplot>
                </el-tab-pane>
            </el-tabs>
            <!-- </div> -->
        </div>
    </div>
</template>

<script>
import * as echarts from "echarts";
import 'echarts-gl';
import boxplot from './boxplot.vue'; // 盒须图
import acrossTable from './acrossTable.vue'; // 横向表格
export default {
    name: 'pageAnalyse',
    emits: [],
    components: { boxplot, acrossTable },
    props: {
        // 布局类型
        layout: { type: String, default: 'one' },
        showClass: { type: Boolean },
        change: {},
        socketObj: { type: Object, default: () => { } },
    },
    watch: {
        change() {
            this.$nextTick(() => {
                setTimeout(this.chartResize, 20)
            })
        },
        socketStatus(val) {
            if (val) this.initUpdateBack();
        },
    },
    computed: {
        socketStatus() {
            return this.socketObj.status
        }
    },
    data() {
        return {
            // 雷达图查询参数
            query: {
                date: new Date(),
            },
            // 表格配置
            columns: [
                { props: 'time', name: '时间', colspan: 2 },
                { props: 'central', name: '频率MHz', colspan: 2 },
                { props: 'pek_num', name: '多径数量', child: { name: '多径', rowspan: 4 } },
                { props: 'pek_db', name: '峰值dB' },
                { props: 'delay', name: '峰值延时ms' },
                { props: 'doppler_shift', name: '峰值频移Hz' },
                { props: 'multi_delay', name: '多径数延时ms', child: { name: '时延域', rowspan: 3 } },
                { props: 'complex_delay_spread', name: '复合多径扩展ms' },
                { props: 'max_delay_spread', name: '最大径内时延扩展ms' },
                { props: 'multi_doppler_offset', name: '多普勒偏移Hz', child: { name: '多普勒域', rowspan: 4 } },
                { props: 'complex_doppler_spread', name: '复合多普勒扩展Hz' },
                { props: 'max_doppler_spread', name: '最大径内多普勒扩展Hz' },
                { props: 'max_doppler_shift', name: '最大多普勒频移Hz' },
                { props: 'complex_co_bw', name: '复合相干带宽Hz', child: { name: '相干', rowspan: 4 } },
                { props: 'effect_co_bw', name: '有效相干带宽Hz' },
                { props: 'complex_co_time', name: '复合相干时间s' },
                { props: 'effect_co_time', name: '有效相干时间s' },
            ],
            // 表格数据
            tableData: {
                time: Array.from({ length: 9 }, (_, index) => null),
                central: Array.from({ length: 9 }, (_, index) => null),
                pek_num: Array.from({ length: 9 }, (_, index) => null),
                pek_db: Array.from({ length: 9 }, (_, index) => null),
                delay: Array.from({ length: 9 }, (_, index) => null),
                doppler_shift: Array.from({ length: 9 }, (_, index) => null),
                multi_delay: Array.from({ length: 9 }, (_, index) => null),
                complex_delay_spread: Array.from({ length: 9 }, (_, index) => null),
                max_delay_spread: Array.from({ length: 9 }, (_, index) => null),
                multi_doppler_offset: Array.from({ length: 9 }, (_, index) => null),
                complex_doppler_spread: Array.from({ length: 9 }, (_, index) => null),
                max_doppler_spread: Array.from({ length: 9 }, (_, index) => null),
                max_doppler_shift: Array.from({ length: 9 }, (_, index) => null),
                complex_co_bw: Array.from({ length: 9 }, (_, index) => null),
                effect_co_bw: Array.from({ length: 9 }, (_, index) => null),
                complex_co_time: Array.from({ length: 9 }, (_, index) => null),
                effect_co_time: Array.from({ length: 9 }, (_, index) => null),
            },
            // 雷达图id
            radarDomId: null,
            // 雷达图对象
            radarChart1: null,
            // 3d图合集id
            chartAllId: null,
            // 3d图合集
            chartAll: null,
            // 默认显示
            activeName: 'MultipathNumber',
            // 盒须图集合
            boxplotList: [
                { name: '多径数', url: 'MultipathNumber', datay1: 'pek_num' },
                { name: '多普勒扩展', url: 'DopplerSpread', datay1: 'max_doppler_spread', datay2: 'complex_doppler_spread' },
                { name: '最大多普勒频移', url: 'MaximumDopplerFrequencyShift', datay1: 'max_doppler_shift' },
                { name: '相干带宽', url: 'CoherentBandwidth', datay1: 'effect_co_bw', datay2: 'complex_co_bw' },
                { name: '时延扩展', url: 'DelaySpread', datay1: 'max_delay_spread', datay2: 'complex_delay_spread' },
                { name: '多普勒偏移', url: 'DopplerShift', datay1: 'multi_doppler_offset' },
                { name: '多径时延', url: 'MultipathDelay', datay1: 'multi_delay' },
                { name: '相干时间', url: 'CoherentTime', datay1: 'effect_co_time', datay2: 'complex_co_time' },
            ],
            // 三维数据配置
            surface: { type: 'surface', data: [], dataShape: [128, 128], silent: true },
            yAxis0: [],
            yAxis1: [],
            // 颜色范围
            max: 0.001,
            min: 0
        }
    },
    created() {
        // 雷达图id
        this.radarDomId = this.$uuid();
        this.chartAllId = this.$uuid();
    },
    mounted() {
        this.$nextTick(() => {
            setTimeout(() => {
                // 初始化图像
                this.initChart();
                // 初始化回调函数和启动接收数据
                this.initUpdateBack();
            }, 100)
        })
    },
    methods: {
        // 雷达图时间发生变化
        changeTime() {
            console.log("变化了:", this.query.date)
        },
        // 初始化socket返回处理函数
        initUpdateBack() {
            if (!this.socketObj) return;
            this.socketBack();
            this.startPush();
        },
        // 设置socket回调函数
        socketBack() {
            // 表格回调函数
            this.socketObj.setMsgBack({
                cmd: 'push-ChannelStatistics',
                fun: rs => {
                    let result = this.formartResult(rs.data);
                    for (let item in this.tableData) {
                        if (item == 'central') result[item][0] = result[item][0] / 10 ** 6;
                        this.tableData[item].unshift(result[item][0]);
                        if (this.tableData[item].length > 30) this.tableData[item] = this.tableData[item].slice(0, 30);
                    }
                },
            })
            // 雷达图回调函数
            this.socketObj.setMsgBack({
                cmd: 'push-ChannelMeasurementRadarDiagram',
                fun: rs => {
                    let { multi_delay = [null], max_doppler_shift = [null], max_doppler_spread = [null], multi_doppler_offset = [null], max_delay_spread = [null], date = [null], time = [null], central = [null] } = this.formartResult(rs.data);
                    let list = [];
                    let title = `${date[0]} ${time[0]}时`;
                    central = (central[0] / 10 ** 6 || 0) + "Mhz" || '';
                    list.push(multi_delay[0]); // 多径延迟
                    list.push(max_doppler_shift[0]) // 最大多普勒频移
                    list.push(max_doppler_spread[0]) // 最大径内多普勒扩展
                    list.push(multi_doppler_offset[0]) // 多普勒偏移
                    list.push(max_delay_spread[0]) // 最大径内时延扩展
                    this.updateCharts1([list], title, central)
                },
            })

            // 三维图回调函数
            this.socketObj.setMsgBack({
                cmd: 'push-ScatteringFunction',
                fun: rs => {
                    let { scf_data, zMax, zMin } = this.formartResult(rs.data);
                    if (zMax && zMax.length > 0) this.max = zMax[0];
                    if (zMin && zMin.length > 0) this.min = zMin[0];
                    this.updateCharts2({ data: { surfaceData: scf_data } })
                },
            })
            // 时延域建模回调函数
            this.socketObj.setMsgBack({
                cmd: 'push-TimeDelayDomainModeling',
                fun: rs => {
                    const { ax_curve_delay = [], fit_curve_delay = [], scf_curve_delay = [] } = this.formartResult(rs.data);
                    this.updateCharts2({ index: 0, data: { datax: ax_curve_delay, linAllList: fit_curve_delay, scatterAllList: scf_curve_delay } })
                },
            })
            // 多普勒域建模回调函数
            this.socketObj.setMsgBack({
                cmd: 'push-DopplerDomainModeling',
                fun: rs => {
                    const { ax_curve_doppler = [], fit_curve_doppler = [], scf_curve_doppler = [] } = this.formartResult(rs.data);
                    this.updateCharts2({ index: 1, data: { datax: ax_curve_doppler, linAllList: fit_curve_doppler, scatterAllList: scf_curve_doppler } })
                },
            })
        },
        // 启动推送消息
        startPush() {
            // 启动频谱图数据接收
            this.socketObj.sendMsg({ cmd: 'start-ChannelMeasurementRadarDiagram' })
            // .then(rs => {
            //     console.log("雷达图启动成功:", rs)
            // })
            // 启动三维图数据
            this.socketObj.sendMsg({ cmd: 'start-ScatteringFunction' })
            // .then(rs => {
            //     console.log("三维图启动成功:", rs)
            // })
            // 启动时延域建模
            this.socketObj.sendMsg({ cmd: 'start-TimeDelayDomainModeling' })
            // .then(rs => {
            //     console.log("时延域建模启动成功:", rs)
            // })
            // 启动多普勒域建模
            this.socketObj.sendMsg({ cmd: 'start-DopplerDomainModeling' })
            // .then(rs => {
            //     console.log("多普勒域建模启动成功:", rs)
            // })
            // 启动信道域表格
            this.socketObj.sendMsg({ cmd: 'start-ChannelStatistics' })
            // .then(rs => { console.log("表格启动成功了：", rs) })
        },
        // socket数据过滤统一处理
        formartResult(result) {
            let { dataLables, data } = result;
            let resultMap = {};
            if (dataLables.length != data.length) {
                return resultMap
            } else {
                for (let i = 0; i < dataLables.length; i++) {
                    resultMap[dataLables[i]] = data[i]
                }
            }
            return resultMap
        },
        // 适配图像
        chartResize() {
            if (!this.radarChart1 || !this.chartAll) {
                this.initChart()
            } else {
                this.radarChart1.resize()
                this.chartAll.resize()
            }
        },
        // 获取当前时间
        getTime() {
            const date = new Date();
            let mon = date.getMonth() + 1;
            let day = date.getDate();
            let houer = date.getHours();
            if (mon < 10) mon = '0' + mon;
            if (day < 10) day = '0' + day;
            // return `${date.getFullYear()}${mon}${day} ${houer}时`
            return `${date.getFullYear()}${mon}${day} `
        },
        // 初始化图形dom
        initChart() {
            this.initChart1();
            this.initChart2();
        },
        // 初始化雷达图
        initChart1(datay, title, central) {
            if (!this.radarChart1) this.radarChart1 = echarts.init(document.getElementById(this.radarDomId));
            let datax = [
                { name: '多径延迟\n10ms', max: 1 },
                { name: '最大多普勒频移\n5Hz', max: 1 },
                { name: '最大径内多普勒扩展\n5Hz', max: 1 },
                { name: '多普勒偏移\n5Hz', max: 1 },
                { name: '最大径内时延扩展\n5ms', max: 1 },
            ]
            this.radarChart1.setOption({
                backgroundColor: '#161627',
                title: [
                    {
                        text: '信道测量雷达图', top: 10,
                        textStyle: { color: '#575D73', fontSize: this.showClass ? '0.9rem' : '18px', } // width: 30, // overflow: 'break' }
                    },
                    { text: `${title || ''}\n${central || ''}`, textStyle: { fontWeight: '400', color: '#575D73', fontSize: this.showClass ? '1rem' : '18px', }, right: 5, top: 10 }
                ],
                radar: { indicator: datax, center: ['50%', '50%'], radius: '60%', nameGap: 5, splitLine: { lineStyle: { color: '#575D73' } }, axisLine: { lineStyle: { color: '#575D73' } }, splitArea: { show: false } },
                series: [
                    {
                        type: 'radar', symbol: 'none',
                        // areaStyle: { color: '#AA9B5F ' },
                        lineStyle: { color: '#AA9B5F', width: 1 },
                        data: datay
                    }
                ]
            });
        },
        // 更新雷达图
        updateCharts1(datay, title, central) {
            if (!this.radarChart1) {
                this.initChart1(datas, title, central);
            } else {
                this.radarChart1.setOption({
                    title: [{}, { text: `${title}\n${central}MHz`, }],
                    series: [{ data: datay }]
                })
            }
        },
        // 初始化3D图合集
        initChart2(series = []) {
            if (!this.chartAll) this.chartAll = echarts.init(document.getElementById(this.chartAllId));
            this.chartAll.setOption({
                tooltip: { trigger: 'none' }, backgroundColor: '#000',
                visualMap: { show: false, seriesIndex: 0, dimension: 2, inRange: { color: ['#1B2A4D', '#ADFDF7'] }, min: this.min, max: this.max },
                xAxis3D: {}, yAxis3D: {}, zAxis3D: {}, grid3D: { left: 0, width: '49%' },
                grid: [
                    { left: '50%', width: '49%', height: '38%', top: '3%' },
                    { left: '50%', width: '49%', height: '38%', bottom: '8%' },
                ],
                xAxis: [
                    { type: 'value', gridIndex: 0, scale: true, boundaryGap: false, splitLine: { show: false }, axisLine: { show: true, onZero: false } },
                    { type: 'value', gridIndex: 1, scale: true, boundaryGap: false, splitLine: { show: false }, axisLine: { show: true, onZero: false } }
                ],
                yAxis: [
                    { type: 'value', splitLine: { show: false }, axisLine: { show: true, onZero: false }, gridIndex: 0 },
                    { type: 'value', splitLine: { show: false }, axisLine: { show: true, onZero: false }, gridIndex: 1 }],
                series: series
            });
        },
        // 更新3D图合集
        updateCharts2(parmary) {
            const { index, data } = parmary;
            // 更新时延域
            const { datax, linAllList = [], scatterAllList = [], surfaceData } = data;
            // 线集合、点集合、三维
            let lineList = [], scatterList = [];
            // 处理二维数据
            for (let i = 0; i < linAllList.length; i++) {
                for (let k in linAllList[i]) {
                    linAllList[i][k] = [datax[k], linAllList[i][k]]
                }
                lineList.push({ data: linAllList[i], xAxisIndex: index, yAxisIndex: index, type: 'line', showSymbol: false, smooth: true, lineStyle: { width: 1 } });
            }
            for (let i = 0; i < scatterAllList.length; i++) {
                for (let k in scatterAllList[i]) {
                    scatterAllList[i][k] = [datax[k], scatterAllList[i][k]]
                }
                scatterList.push({ data: scatterAllList[i], xAxisIndex: index, yAxisIndex: index, symbolSize: 2, type: 'scatter' });
            }
            // 替换掉三维数据
            if (surfaceData) this.surface.data = surfaceData;
            // 替换掉二维数据
            if (index == 0) {
                this.yAxis0 = [...lineList, ...scatterList]
            }
            if (index == 1) {
                this.yAxis1 = [...lineList, ...scatterList]
            }

            // 组合数据体
            let series = [this.surface, ...this.yAxis0, ...this.yAxis1];
            // if (surfaceData && surfaceData.length > 0) series.push(surface);
            // series.push(...lineList, ...scatterList);
            if (!this.chartAll) {
                this.initChart2(series);
            } else {
                // 获取原始数据
                // let option = this.chartAll.getOption();
                // let seriesList = option.series.filter(item => item.xAxisIndex != index && item.type != 'surface');
                // let one = option.series.filter(item => item.type == 'surface');
                // if (!surface) surface = one;
                // if (!surfaceData && one) series[0] = one;
                this.chartAll.setOption({
                    visualMap: { max: this.max, min: this.min },
                    series: series
                    // [
                    //     ...series,
                    //     ...seriesList

                    // ]
                })
            }
        },
    },
    beforeDestroy() {
        // 删除socket的数据监听
        if (this.socketObj) {
            // 停止推送
            this.socketObj.sendMsg({ cmd: 'stop-ChannelMeasurementRadarDiagram' });
            this.socketObj.sendMsg({ cmd: 'stop-ScatteringFunction' });
            this.socketObj.sendMsg({ cmd: 'stop-TimeDelayDomainModeling' });
            this.socketObj.sendMsg({ cmd: 'stop-DopplerDomainModeling' });
            // 删除处理函数
            this.socketObj.removeMsgBack({ cmd: 'push-ChannelMeasurementRadarDiagram' })
            this.socketObj.removeMsgBack({ cmd: 'push-ScatteringFunction' })
            this.socketObj.removeMsgBack({ cmd: 'push-TimeDelayDomainModeling' })
            this.socketObj.removeMsgBack({ cmd: 'push-DopplerDomainModeling' })

        }
    }
}
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
.float-left {
    width: 25%;
    height: 50%;
    float: left;
}

.boxplot-box {
    ::v-deep.el-tabs__header {
        height: 30px;
    }

    ::v-deep.el-tabs__content {
        height: calc(100% - 30px);
    }

    ::v-deep.el-tab-pane {
        height: 100%;
    }

    ::v-deep.el-tabs__item {
        color: #9A9DAA;
    }

    ::v-deep.el-tabs__item.is-active {
        color: #FFFFFF;
    }
}

.el-input {
    width: 11rem;
}

.el-input--medium {
    font-size: 1rem;
    line-height: 2rem;
}

.radar-input {
    ::v-deep.el-input__inner {
        height: 2.5rem;
        line-height: 2.5rem;
        font-size: 1rem;
        padding-left: 2.5rem;
        padding-right: 2rem;
    }

    ::v-deep.el-input__icon {
        line-height: 2.5rem;
    }

    ::v-deep.el-input__prefix {
        left: 0.1rem;
    }

    ::v-deep.el-input__icon {
        width: 2rem;
    }
}
</style>